package validator

import (
	"errors"
	"github.com/gin-gonic/gin"
	ut "github.com/go-playground/universal-translator"
	"gopkg.in/go-playground/validator.v9"
	"strings"
)

func ParseParamsAndValidate(ctx *gin.Context, params interface{}) error {
	if err := ctx.ShouldBind(params); err != nil {
		return err
	}
	iValidator, err := GetValidator(ctx)
	if err != nil {
		return err
	}
	//获取翻译器
	iTanslator, err := GetTranslation(ctx)
	if err != nil {
		return err
	}
	//参数 转为 结构体 实体
	err = iValidator.Struct(params)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		sliceErrs := []string{}
		for _, e := range errs {
			//翻译对应的错误 信息
			sliceErrs = append(sliceErrs, e.Translate(iTanslator))
		}
		return errors.New(strings.Join(sliceErrs, ","))
	}
	return nil
}

/* =================================================================
	从 gin中 获取 验证器
 * =================================================================*/
func GetValidator(ctx *gin.Context) (*validator.Validate, error) {
	val, ok := ctx.Get(ValidatorKey)
	if !ok {
		return nil, errors.New("未设置验证器")
	}

	validator, ok := val.(*validator.Validate)
	if !ok {
		return nil, errors.New("获取验证器失败")
	}
	return validator, nil
}

/* =================================================================
	获取翻译器
 * =================================================================*/
func GetTranslation(ctx *gin.Context) (ut.Translator, error) {
	trans, ok := ctx.Get(TranslatorKey)
	if !ok {
		return nil, errors.New("未设置翻译器")
	}
	translator, ok := trans.(ut.Translator)
	if !ok {
		return nil, errors.New("获取翻译器失败")
	}
	return translator, nil
}
